# coding: utf-8

import json

import time
from flask import request

from fralog.FraLog import getFileLog
from exceptions.fra_exception import FraException
from settings import *
from dbproxy.dbproxy import *

log = getFileLog()
# 根据题号,题目属性查找标准问卷模板 ok
# 根据编号/题目属性查找标准题目--重复
# 查询常模列表--重复
# 新增常模
# 保存标准问卷模板

log = getFileLog()


class StandardCombine(object):
    """
    客户题库相关操作的接口功能均封装在此
    """
    table_name = 'surveys_collection'

    def __init__(self):
        super(StandardCombine, self).__init__()
        self.db_proxy = DBProxy(db=mongo)

    def query_survey(self, pagesize=1000, page=1, survey_id=None, survey_type=None, ):
        """
        根据题号 题目属性 查找问卷模板 (仅仅模型问卷模板)
        :param pagesize
        :param page
        :return:
        'question_id':question_id,'type':type,
        """
        log.debug('查询')
        log.debug('查询模型题库')
        if survey_id is None and survey_type is None:
            ret = self.db_proxy.page_query(table=self.table_name,
                                           # query={'survey_type': {'$or':[{'$lte': 1}]}},
                                           query={'$or': [{'survey_type': 10}, {'survey_type': {'$lte': 2}}]},
                                           page=page, pagesize=pagesize)
        if survey_id is None and survey_type is not None:
            ret = self.db_proxy.page_query(table=self.table_name, query={'survey_type': survey_type},
                                           page=page, pagesize=pagesize)
        if survey_id is not None:
            ret = self.db_proxy.page_query(table=self.table_name, query={'survey_id': survey_id},
                                           page=page, pagesize=pagesize)
        ret['typelist'] = ['标准大五', '特征问卷', '客户问卷']
        log.debug('查询成功返回')
        return ret

    def query_detail(self, survey_id):
        log.debug(' : %s' % (survey_id))
        ret = self.db_proxy.query_one(table=self.table_name, query={'survey_id': survey_id})
        log.debug(' ')
        return ret

    def query_detail_bycode(self, code):
        log.debug(' : %s' % (code))
        ret = self.db_proxy.query_one(table=self.table_name, query={'code': code})
        log.debug(' ')
        return ret

    def query_question_detail(self, question_id):
        log.debug(' : %s' % (question_id))
        ret = self.db_proxy.query_one(table='questions_collection', query={'question_id': question_id})
        log.debug(' ')
        return ret

    def edit(self, survey_id, setvalue, insert_not_found=False):
        log.debug(' ')
        if insert_not_found is True:
            setvalue['$inc'] = {'survey_id': 1}
        ret = self.db_proxy.update(table=self.table_name, query={'survey_id': survey_id}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        return ret

    def insert(self, value):
        log.debug('插入标准组卷')
        lastItem = self.db_proxy.query_lastone(table=self.table_name, field="survey_id")
        if len(lastItem['data']) > 0:
            value["survey_id"] = lastItem['data'][0]["survey_id"] + 1
        else:
            value["survey_id"] = 1
        # value['$inc'] = {'survey_id': 1}
        ret = self.db_proxy.insert(table=self.table_name, value=value)
        return ret

    def edit_add_normal_collection(self, code, setvalue, insert_not_found=True):
        log.debug(' ')
        ret = self.db_proxy.update(table='normal_collection', query={'code': code}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)

        return ret

    def delete(self, survey_id):
        log.debug(' : %s' % (survey_id))
        ret = self.db_proxy.delete(table=self.table_name, query={'survey_id': survey_id})
        return ret

    def query_jump_survey(self, param):
        """
        根据 公司名 问卷标题 查找问卷模板
        """
        log.debug('查询模型题库')
        page = param.get('page')
        if page is None or page == '':
            page = 1
        pagesize = param.get('pagesize')
        if pagesize is None or pagesize == '':
            pagesize = 100
        company_id = param.get('company_id')
        title = param.get('title')
        query_params = {'$and': []}
        if company_id is not None and company_id != "":
            query_params['$and'].append({"company_id": {"$regex": str(company_id)}})
        if title is not None and title != "":
            query_params['$and'].append({"title": {"$regex": str(title)}})
        if len(query_params['$and']) == 0:
            query_params = {}
        ret = self.db_proxy.page_query(table=self.table_name, query=query_params, page=page, pagesize=pagesize,
                                       sort=[('create_time', pymongo.DESCENDING)])
        log.debug('查询成功返回')
        return ret

    def get_jump_survey_detail(self, param):
        """
        根据 问卷code 查找问题列表
        """
        log.debug('查询模型题库')
        code = param.get('code')
        ret = {}
        if code is None or code == '':
            ret['code'] = 500
            ret['msg'] = '参数错误'
        else:
            surveys_result = self.db_proxy.page_query(table=self.table_name, query={'code': code})
            surveys = surveys_result['data']
            if surveys is None or len(surveys) == 0 or surveys[0]['questions'] is None \
                    or not isinstance(surveys[0]['questions'].split(','), list):
                ret['code'] = 500
                ret['msg'] = '查询为空'
            else:
                q_ids = []
                for q_id in surveys[0]['questions'].split(','):
                    q_ids.append(int(q_id))
                log.debug('查询模型题库00-' + str(surveys[0]['questions'].split(',')))
                ret = self.db_proxy.page_query(table="questions_collection", query={'question_id': {'$in': q_ids}})
                log.debug('查询成功返回')
        return ret

    def get_jump_rules(self, param):
        """
        根据 问卷编码 查询跳转规则
        """
        log.debug('查询跳转规则')
        code = param.get('code')
        ret = {}
        if code is None or code == '':
            ret['code'] = 500
            ret['msg'] = '查询为空'
        else:
            surveys_result = self.db_proxy.page_query(table=self.table_name, query={'code': code})
            surveys = surveys_result.get('data')[0]
            question_ids = surveys.get('questions').strip(',').split(',')   # 问卷的题目存在 questions 字段里，题目以逗号分隔符存储，如，1,2,3,4,5
            end_question_id = None
            if len(question_ids) > 0:
                end_question_id = int(question_ids[len(question_ids)-1])

            total_questions = []
            for qu in question_ids:
                question_id = int(qu)
                question_item = self.db_proxy.query_one(table="questions_collection", query={'question_id': int(question_id)})
                if end_question_id == question_id:
                    total_questions.append(
                        {
                            "code": code,
                            "end_flag": True,
                            "temp_end_flag": True,
                            "question_id": question_id,
                            "type": question_item.get('data')[0].get('type'),
                            "question_title": question_item.get('data')[0].get('question_title')
                        })
                else:
                    total_questions.append(
                        {
                            "code": code,
                            "end_flag": False,
                            "question_id": question_id,
                            "type": question_item.get('data')[0].get('type'),
                            "question_title": question_item.get('data')[0].get('question_title')
                        }
                    )
            combin_questions = []
            for item in total_questions:
                ret = self.db_proxy.page_query(table="t_jump_rule",
                                               query={'code': code, 'question_id': item.get('question_id')})
                it = None
                if ret.get('count') > 0:
                    it = ret.get('data')[0]
                else:
                    it = item
                if 'end_flag' not in it:
                    it['end_flag'] = False
                if 'tag_url' not in it:
                    it['tag_url'] = None
                if 'max_select' not in it:
                    it['max_select'] = 100
                it['type'] = item['type']
                it['question_title'] = item['question_title']
                if 'temp_end_flag' in item:
                    it['temp_end_flag'] = item['temp_end_flag']
                combin_questions.append(it)
        ret['count'] = len(combin_questions)
        ret['data'] = combin_questions
        log.debug('查询成功返回')
        return ret

    def submit_jump_rules(self, param):
        """
        根据 问卷编码 提交跳转规则
        """
        log.debug('提交跳转规则')
        print(param)
        rules = param.get('rules')
        code = rules[0].get('code')
        ret = {}
        if code is None or code == '' or rules is None or not isinstance(rules, list):
            ret['code'] = 500
            ret['msg'] = '参数错误'
        else:
            self.db_proxy.delete(table="t_jump_rule", query={'code': code})
            for rule in rules:
                if 'max_select'in rule and 'code' in rule and 'end_flag' in rule and 'question_id' in rule \
                        and 'question_title' in rule and 'tag_url' in rule and 'type' in rule:
                    if 'temp_end_flag' in rule:
                        if rule['end_flag'] is True and rule['tag_url'] is None and rule['max_select'] == 100:
                            if len(rule) == 8:
                                continue
                    else:
                        if rule['end_flag'] is False and rule['tag_url'] is None and rule['max_select'] == 100:
                            if len(rule) == 7:
                                continue
                rule['code'] = code
                if rule['tag_url'] is not None and rule['tag_url'].strip() == '':
                    rule['tag_url'] = None
                if 'temp_end_flag' in rule:
                    del rule['temp_end_flag']
                self.db_proxy.insert(table="t_jump_rule", value=rule)
            ret['code'] = 200
            ret['msg'] = '处理成功'
        log.debug('查询成功返回')
        return ret


standard_combine = StandardCombine()


@app.route('/sc/query_survey', methods=['GET', 'POST'])
@verify_token
def sc_query_very():
    '''
    默认查询标准和特征组卷模板,不含用户组卷模板;
    如不填不含用户组卷模板,如填按填的查询
    输入:survey_id , survey_type 可不填
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug('查询模板')
    param = get_param(request)
    survey_id = param.get('survey_id')
    if survey_id is not None:
        if str(survey_id).isdigit():
            survey_id = int(survey_id)
        else:
            survey_id = 0
    survey_type = param.get('survey_type')
    if survey_type is not None and survey_type != '':
        survey_type = int(survey_type)
    if survey_type == '':
        survey_type = None
    return json.dumps(standard_combine.query_survey(survey_id=survey_id, survey_type=survey_type))


@app.route('/sc/query_survey2', methods=['GET', 'POST'])
@verify_token
def sc_query_survey():
    '''
    无参数默认查询标准和特征组卷模板,不含用户组卷模板;
    输入:无
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    # survey_type = param.get('survey_type')
    return json.dumps(standard_combine.query_survey(param))


@app.route('/sc/query_detail', methods=['GET', 'POST'])
@verify_token
def sc_query_detail():
    '''
    查询组卷模板;
    输入:survey_id
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    survey_id = param.get('survey_id')
    if survey_id is not None:
        survey_id = int(survey_id)
    return json.dumps(standard_combine.query_detail(survey_id))


@app.route('/sc/query_detail_bycode', methods=['GET', 'POST'])
@verify_token
def sc_query_detail_bycode():
    '''
    查询组卷模板;
    输入:survey_id
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    code = param.get('code')
    return json.dumps(standard_combine.query_detail_bycode(code))


@app.route('/sc/edit', methods=['GET', 'POST'])
@verify_token
def sc_edit():
    '''
    修改组卷模板;
    输入:survey_id
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    survey_id = param.get('survey_id')
    del param['token']
    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    param['update_time'] = timestr
    return json.dumps(standard_combine.edit(survey_id=survey_id, setvalue=param))


@app.route('/sc/insert', methods=['GET', 'POST'])
@verify_token
def sc_insert():
    '''
    新增组卷模板;
    输入:survey_id 等组卷表字段属性
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    # survey_id = param.get('survey_id')
    del param['token']
    # 根据survey_type确定标准问卷操作和特征问卷操作
    # 标准问卷的话,questions数组根据题目类型加入OCEAN_scoring中
    # 特征问卷的话,questions数组根据题目加入rule_scoring中
    # if param
    O_scoring = []
    C_scoring = []
    E_scoring = []
    A_scoring = []
    N_scoring = []
    rule_scoring = []
    macroquestions = param.get('questions')
    if param['survey_type'] == 1:
        param['rule_scoring'] = param['questions']
    if param['select_survey_type'] == 0:
        questions = macroquestions.split(',')
        for key in questions:  # each
            set = standard_combine.query_question_detail(question_id=int(key))
            row = set.get('data')[0]
            if row.get('question_dim') == 'O':
                if row.get('polar_type') == -1:
                    O_scoring.append(str(row.get('question_id')) + 'R')
                else:
                    O_scoring.append(str(row.get('question_id')))
            if row.get('question_dim') == 'C':
                if row.get('polar_type') == -1:
                    C_scoring.append(str(row.get('question_id')) + 'R')
                else:
                    C_scoring.append(str(row.get('question_id')))
            if row.get('question_dim') == 'E':
                if row.get('polar_type') == -1:
                    E_scoring.append(str(row.get('question_id')) + 'R')
                else:
                    E_scoring.append(str(row.get('question_id')))
            if row.get('question_dim') == 'A':
                if row.get('polar_type') == -1:
                    A_scoring.append(str(row.get('question_id')) + 'R')
                else:
                    A_scoring.append(str(row.get('question_id')))
            if row.get('question_dim') == 'N':
                if row.get('polar_type') == -1:
                    N_scoring.append(str(row.get('question_id')) + 'R')
                else:
                    N_scoring.append(str(row.get('question_id')))
        ostr = ''
        for i in range(0, len(O_scoring)):
            if i == 0:
                ostr = O_scoring[i]
            else:
                ostr = ostr + ',' + O_scoring[i]
        cstr = ''
        for i in range(0, len(C_scoring)):
            if i == 0:
                cstr = C_scoring[i]
            else:
                cstr = cstr + ',' + C_scoring[i]
        estr = ''
        for i in range(0, len(E_scoring)):
            if i == 0:
                estr = E_scoring[i]
            else:
                estr = estr + ',' + E_scoring[i]
        astr = ''
        for i in range(0, len(A_scoring)):
            if i == 0:
                astr = A_scoring[i]
            else:
                astr = astr + ',' + A_scoring[i]
        nstr = ''
        for i in range(0, len(N_scoring)):
            if i == 0:
                nstr = N_scoring[i]
            else:
                nstr = nstr + ',' + N_scoring[i]
        param['O_scoring'] = ostr
        param['C_scoring'] = cstr
        param['E_scoring'] = estr
        param['A_scoring'] = astr
        param['N_scoring'] = nstr
        current_time = time.localtime(time.time())
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        param['create_time'] = timestr
    if param['select_survey_type'] == 10:
        questions = macroquestions.split(',')
        for key in questions:  # each
            set = standard_combine.query_question_detail(question_id=int(key))
            row = set.get('data')[0]
            if row.get('question_type') == 0:
                if row.get('question_dim') == 'O':
                    if row.get('polar_type') == -1:
                        O_scoring.append(str(row.get('question_id')) + 'R')
                    else:
                        O_scoring.append(str(row.get('question_id')))
                if row.get('question_dim') == 'C':
                    if row.get('polar_type') == -1:
                        C_scoring.append(str(row.get('question_id')) + 'R')
                    else:
                        C_scoring.append(str(row.get('question_id')))
                if row.get('question_dim') == 'E':
                    if row.get('polar_type') == -1:
                        E_scoring.append(str(row.get('question_id')) + 'R')
                    else:
                        E_scoring.append(str(row.get('question_id')))
                if row.get('question_dim') == 'A':
                    if row.get('polar_type') == -1:
                        A_scoring.append(str(row.get('question_id')) + 'R')
                    else:
                        A_scoring.append(str(row.get('question_id')))
                if row.get('question_dim') == 'N':
                    if row.get('polar_type') == -1:
                        N_scoring.append(str(row.get('question_id')) + 'R')
                    else:
                        N_scoring.append(str(row.get('question_id')))
            if row.get('question_type') == 1:
                rule_scoring.append(str(row.get('question_id')))

        rulestr = ''
        for i in range(0, len(rule_scoring)):
            if i == 0:
                rulestr = rule_scoring[i]
            else:
                rulestr = rulestr + ',' + rule_scoring[i]
        ostr = ''
        for i in range(0, len(O_scoring)):
            if i == 0:
                ostr = O_scoring[i]
            else:
                ostr = ostr + ',' + O_scoring[i]
        cstr = ''
        for i in range(0, len(C_scoring)):
            if i == 0:
                cstr = C_scoring[i]
            else:
                cstr = cstr + ',' + C_scoring[i]
        estr = ''
        for i in range(0, len(E_scoring)):
            if i == 0:
                estr = E_scoring[i]
            else:
                estr = estr + ',' + E_scoring[i]
        astr = ''
        for i in range(0, len(A_scoring)):
            if i == 0:
                astr = A_scoring[i]
            else:
                astr = astr + ',' + A_scoring[i]
        nstr = ''
        for i in range(0, len(N_scoring)):
            if i == 0:
                nstr = N_scoring[i]
            else:
                nstr = nstr + ',' + N_scoring[i]
        param['O_scoring'] = ostr
        param['C_scoring'] = cstr
        param['E_scoring'] = estr
        param['A_scoring'] = astr
        param['N_scoring'] = nstr
        param['rule_scoring'] = rulestr
        current_time = time.localtime(time.time())
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        param['create_time'] = timestr
        param['survey_version'] = 2
    return json.dumps(standard_combine.insert(value=param))


@app.route('/sc/edit_add_normal_collection', methods=['GET', 'POST'])
@verify_token
def sc_edit_add_normal_collection():
    log.debug(' ')
    '''
    新增或修改常模表;
    输入:code 等常模表字段属性
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    code = param.get('code')
    del param['token']
    return json.dumps(standard_combine.edit_add_normal_collection(code=code, setvalue=param, insert_not_found=True))


@app.route('/sc/delete', methods=['GET', 'POST'])
@verify_token
def sc_delete():
    '''
    删除组卷模板;
    输入:survey_id
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    survey_id = int(param.get('survey_id'))
    return json.dumps(standard_combine.delete(survey_id=survey_id))


@app.route('/sc/jump/query_page', methods=['GET', 'POST'])
# @verify_token
def sc_jump_query_page():
    '''
    分页查询问卷;
    输入:
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    return jsonify(standard_combine.query_jump_survey(param))


@app.route('/sc/jump/get_survey_detail', methods=['GET', 'POST'])
# @verify_token
def get_jump_survey_detail():
    '''
    分页查询问卷;
    输入:
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    return json.dumps(standard_combine.get_jump_survey_detail(param))


@app.route('/sc/jump/get_rules', methods=['GET', 'POST'])
# @verify_token
def get_jump_rules():
    '''
    分页查询问卷;
    输入:
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    return jsonify(standard_combine.get_jump_rules(param))


@app.route('/sc/jump/submit_rules', methods=['GET', 'POST'])
# @verify_token
def submit_jump_rules():
    '''
    分页查询问卷;
    输入:
    返回:ret集合,成功ret.code=200,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    return jsonify(standard_combine.submit_jump_rules(param))
